package cn.lanqiao.chatroom;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

public class TestSockServer {

    public static Vector<Tony> list = new Vector<>();

    public static void main(String[] args) {
        Socket socket = null;
        try {
            //1、开门
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务器已经启动！");
            while (true) {
                //2、等待顾客
                socket = serverSocket.accept();
                //3、新建tony对象
                Tony tony = new TestSockServer().new Tony(socket);
                tony.start();
                //4、将顾客分配给tony对象
                //tony.setSocket(socket);
                //tony.start();
                //5、本子记录关系
                list.add(tony);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class Tony extends Thread {
        private Socket socket; //顾客

        public Tony(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            DataOutputStream dos = null;
            DataInputStream dis = null;
            try {
                // 提供服务
                dos = new DataOutputStream(socket.getOutputStream());
                dis = new DataInputStream(socket.getInputStream());
                String str = null;
                while ((str = dis.readUTF()) != null) {
                    // 广播给所有用户 list
                    for (Tony tony : list){
                        dos = new DataOutputStream(tony.socket.getOutputStream());
                        dos.writeUTF(this.getName() + "：" + str);
                    }
                    //断开连接
                    if (str.equals("88")) {
                        System.out.println("客户端断开连接！");
                        list.remove(this);
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    dis.close();
                    dos.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

